package com.baidu.ueditor.upload;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.suixun.utils.Constants;
import com.suixun.utils.HttpUtil;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.util.Arrays;
import java.util.Map;

public final class Base64Uploader {

	public static State save(String content, Map<String, Object> conf) {

		byte[] data = decode(content);

		long maxSize = ((Long) conf.get("maxSize")).longValue();

		if (!validSize(data, maxSize)) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

		String suffix = FileType.getSuffix("JPG");

		String savePath = PathFormat.parse((String) conf.get("savePath"), (String) conf.get("filename"));

		savePath = savePath + suffix;
		String physicalPath = (String) conf.get("rootPath") + savePath;

		State storageState = StorageManager.saveBinaryFile(data, physicalPath);

		if (storageState.isSuccess()) {
			storageState.putInfo("url", PathFormat.format(savePath));
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", "");
		}

		return storageState;
	}

	/**
	 * 
	 * 功能描述: 和save方法一样，只是将rootPath改为了savePath，并调用公共的上传文件接口
	 * @param content
	 * @param conf
	 * @return
	 */
	public static State savePlus(String content, Map<String, Object> conf) {

		byte[] data = decode(content);

		long maxSize = ((Long) conf.get("maxSize")).longValue();

		if (!validSize(data, maxSize)) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

		String suffix = FileType.getSuffix("JPG");

		String savePath = PathFormat.parse((String) conf.get("savePath"), (String) conf.get("filename"));

		savePath = savePath + suffix;
		String physicalPath = (String) conf.get("rootPath") + savePath;

		// 1.先将文件保存在本地，2.上传到公共文件地方，3.删除本地文件
		// 1.将文件保存在本地
		State storageState = StorageManager.saveBinaryFile(data, physicalPath);
		
		// 2.上传到公共文件地方，这里调用公共的上传文件接口
		File file = new File(physicalPath);
		HttpUtil.uploadFile((String) conf.get("baseUploadPath") + "?token=" + Constants.getToken() + "&url=" + savePath,
				Arrays.asList(file));
		// 3.删除本地文件
		file.delete();

		if (storageState.isSuccess()) {
			storageState.putInfo("url", PathFormat.format(savePath));
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", "");
		}

		return storageState;
	}

	private static byte[] decode(String content) {
		return Base64.decodeBase64(content);
	}

	private static boolean validSize(byte[] data, long length) {
		return data.length <= length;
	}

}